package gis.network.http;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import gis.activities.MapShowActivity;
import gis.dto.GPS_Record;
import inter.Download;
import inter.DownloadInfo;
import managers.VolleySingleton;
import utils.ConvertProjection;
import utils.Gps;
import utils.MeasureArea;
import utils.PositionUtil;

import static com.baidu.mapapi.utils.CoordinateConverter.CoordType.GPS;

/**
 * 面积处理
 */

public class AreaOperator {

    // 添加新的地块
    public void addNewArea(final MapShowActivity.Area area, final Response mResponse) {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/SaveGPSInfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.startsWith("{")) {
                            Download2 download = new Gson().fromJson(response, Download2.class);
                            if (download.getStatus() == DownloadInfo.SUCCESS) {
                                mResponse.onResult(true, download);
                            } else {
                                mResponse.onResult(false, null);
                            }
                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mResponse.onResult(false, null);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                GPS_Record gps_record = new GPS_Record();
                gps_record.setRemark(area.getInfo());
                gps_record.setType(area.getType());
                gps_record.setAccount(MyApplication.getOwnUser().getUser_RealName());
                gps_record.setArea(area.getArea() + "");
                gps_record.setId(0);
                StringBuilder record = new StringBuilder("");
                for (LatLng latLng : area.getPoints()) {
                    Gps gps = PositionUtil.bd09_To_Gps84(latLng.latitude,latLng.longitude);
//                    record.append(latLng.latitude + "," + latLng.longitude + ";");
                    record.append(gps.getWgLat()+","+gps.getWgLon()+";");
                }
                gps_record.setRecord(record.toString());
                double x = 0, y = 0;
                for (LatLng l : area.getPoints()) {
                    Gps gps = PositionUtil.bd09_To_Gps84(l.latitude,l.longitude);
                    x += gps.getWgLat();
                    y += gps.getWgLon();
                }
                int lenth = area.getPoints().size();
                if (lenth != 0) {

                    x = x / lenth;
                    y = y / lenth;
                    gps_record.setMiddlePoint(x + "," + y);
                }

                // 计算当前地块所属范围ID
//                Gps gps = PositionUtil.bd09_To_Gps84(x, y);
                Double[] result = ConvertProjection.Convert(y, x);
                int xID = new Double(Math.floor((result[0] - MeasureArea.LEFT) / 1000)).intValue();
                int yID = new Double(Math.floor((MeasureArea.TOP - result[1]) / 1000)).intValue();
                int xyID = xID * 100000 + yID;
                gps_record.setRegion(xyID);
                gps_record.setX(xID);
                gps_record.setY(yID);
//                gps_record.setRemark("");
                gps_record.setTime(Calendar.getInstance());
                map.put("data", new Gson().toJson(gps_record));
                return map;
            }

            @Override
            protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return com.android.volley.Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);

    }

    // 改变已有的地块
    public void changeArea(final MapShowActivity.Area area, final Response mResponse) {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/UpdateGPSINfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.startsWith("{")) {
                            Download download = new Gson().fromJson(response, Download.class);
                            if (download.getStatus() == DownloadInfo.SUCCESS) {
                                mResponse.onResult(true, null);
                            } else {
                                mResponse.onResult(false, null);
                            }
                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mResponse.onResult(false, null);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                GPS_Record gps_record = new GPS_Record();
                gps_record.setAccount(MyApplication.getOwnUser().getUser_RealName());
                gps_record.setArea(area.getArea() + "");
                gps_record.setId(area.getId());
                StringBuilder record = new StringBuilder("");
                for (LatLng latLng : area.getPoints()) {
                    // 百度坐标转化为GPS坐标
                    Gps gps = PositionUtil.bd09_To_Gps84(latLng.latitude,latLng.longitude);
//                    record.append(latLng.latitude + "," + latLng.longitude + ";");
                    record.append(gps.getWgLat()+","+gps.getWgLon()+";");
                }
                gps_record.setRecord(record.toString());

                double x = 0, y = 0;
                for (LatLng l : area.getPoints()) {
                    Gps gps = PositionUtil.bd09_To_Gps84(l.latitude,l.longitude);
                    x += gps.getWgLat();
                    y += gps.getWgLon();
                }
                int lenth = area.getPoints().size();
                if (lenth != 0) {
                    x = x / lenth;
                    y = y / lenth;
                    gps_record.setMiddlePoint(x + "," + y);
                }

                // 计算当前地块所属范围ID
//                Gps gps = PositionUtil.bd09_To_Gps84(x, y);
                Double[] result = ConvertProjection.Convert(y, x);

                int xID = new Double(Math.floor((result[0] - MeasureArea.LEFT) / 1000)).intValue();
                int yID = new Double(Math.floor((MeasureArea.TOP - result[1]) / 1000)).intValue();
                int xyID = xID * 100000 + yID;
                gps_record.setRegion(xyID);
                gps_record.setX(xID);
                gps_record.setY(yID);
//                gps_record.setRemark("");
                gps_record.setTime(Calendar.getInstance());
                map.put("data", new Gson().toJson(gps_record));
                return map;
            }

            @Override
            protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return com.android.volley.Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);

    }

    // 获取附近的地块
    public void getNearByArea(final int region, final Response mResponse) {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/GetGPSInfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.startsWith("{")) {
                            NearByDownload download = new Gson().fromJson(response, NearByDownload.class);
                            if (download.getStatus() == DownloadInfo.SUCCESS) {

                                mResponse.onResult(true, download);
                            } else {
                                mResponse.onResult(false, null);
                            }
                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mResponse.onResult(false, null);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("region", region + "");
                return map;
            }

            @Override
            protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return com.android.volley.Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }


    // 按年获取地块
    public void getAreaByYear(final int year, final Response mResponse) {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/SearchByYear";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.startsWith("{")) {
                            NearByDownload download = new Gson().fromJson(response, NearByDownload.class);
                            if (download.getStatus() == DownloadInfo.SUCCESS) {
                                mResponse.onResult(true, download);
                            } else {
                                mResponse.onResult(false, null);
                            }
                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mResponse.onResult(false, null);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("year", year + "");
                return map;
            }

            @Override
            protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return com.android.volley.Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }


    // 按年获取地块
    public void deleteArea(final long areaID, final Response mResponse) {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/DeleteAreaByID";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.startsWith("{")) {
                            Download download = new Gson().fromJson(response, Download.class);
                            if (download.getStatus() == DownloadInfo.SUCCESS) {
                                mResponse.onResult(true, download);
                            } else {
                                mResponse.onResult(false, null);
                            }
                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mResponse.onResult(false, null);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("areaID", areaID + "");
                return map;
            }

            @Override
            protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return com.android.volley.Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }


    public static class Response {
        public void onResult(boolean success, Object result) {
        }

        ;
    }

    public static class NearByDownload {
        int status;
        List<GPS_Record> records = new ArrayList<>();

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<GPS_Record> getRecords() {
            return records;
        }

        public void setRecords(List<GPS_Record> records) {
            this.records = records;
        }
    }

    // 上传GPS坐标后返回id信息
    public static class Download2 {

        int status;
        long id;


        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }


    }


}
